package com.springboot.demo.util;

import cn.hutool.core.io.file.LineSeparator;
import cn.hutool.http.HttpUtil;
import com.springboot.demo.config.SmsConfig;
import org.apache.commons.codec.digest.DigestUtils;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

import static cn.hutool.http.HttpUtil.post;

/**
 * @Author: J.K
 * @Date: 2021-09-10 13:39
 * @Description: 发送短信验证码
 */
public class SendNumUtil {
    /**
     * 获取当前时间字符串
     *
     * @return
     */
    public static String getDateTime() {
        DateTimeFormatter dateFormatter = DateTimeFormatter.ofPattern("yyyyMMddHHmmss");
        String dateTime = LocalDateTime.now().format(dateFormatter);
        return dateTime;
    }

    public static void sendSms(String to) {
        String tmpSmsContent = null;
        try {
            tmpSmsContent = URLEncoder.encode(SmsConfig.smsContent, "utf-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        String url = SmsConfig.BASE_URL;
        String body = "accountSid=" + SmsConfig.ACCOUNT_SID + "&to=" + to + "&smsContent=" + tmpSmsContent + createCommonParam();
        String result = post(url, body);
        System.out.println("result:"+ System.lineSeparator()+result);
    }

    /**
     * 构建请求完整url
     *
     * @return
     */
    private static String createCommonParam() {
        // 签名
        String signature = DigestUtils.md5Hex(SmsConfig.ACCOUNT_SID + SmsConfig.AUTH_TOKEN + getDateTime());
        return "&timestamp=" + getDateTime() + "&sig=" + signature + "&respDataType=" + SmsConfig.RESP_DATA_TYPE;
    }
}
